package caches

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"
	"xiegao/models"
)

type Auth struct {
	Cache cache.Cache
}

func (self *Auth) GetUser(code string) *models.WeiXinUser{
	client := &http.Client{Timeout: time.Second * 10}
	Base, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	wxConfig, readError := config.NewConfig("ini", filepath.Join(Base, "conf/weixin.conf"))
	if readError != nil {
		panic("找不到配置文件")
	}
	response, _ := client.Get(
		fmt.Sprintf(
			"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
			wxConfig.String("appid"),
			wxConfig.String("appsecret"),
			code,
		),
	)
	defer response.Body.Close()
	byteBody,error := ioutil.ReadAll(response.Body)
	if error != nil{
		panic("获取AuthAccessToken失败")
	}
	var accesstoken map[string]interface{}
	marshalerror := json.Unmarshal(byteBody,&accesstoken)
	if marshalerror != nil{
		fmt.Print(marshalerror)
		panic("读取AuthAccessToken失败")
	}
	fmt.Println(accesstoken)
	error = self.Cache.Put(accesstoken["openid"].(string),accesstoken,time.Hour * 24 * 30)
	if error != nil{
		panic("缓存AuthAccessToken失败")
	}
	user_info_response, _ := client.Get(
		fmt.Sprintf(
			"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
			accesstoken["access_token"].(string),
			accesstoken["openid"].(string),
		),
	)
	defer user_info_response.Body.Close()
	var user_info map[string]interface{}
	byte_user_info ,_ := ioutil.ReadAll(user_info_response.Body)
	error = json.Unmarshal(byte_user_info,&user_info)
	if error != nil{
		panic("获取用户信息失败")
	}
	fmt.Println(user_info)
	user := &models.WeiXinUser{
		Nickname:user_info["nickname"].(string),
		Openid:user_info["openid"].(string),
		Sex:strconv.Itoa(int(user_info["sex"].(float64))),
		Province:user_info["province"].(string),
		City:user_info["city"].(string),
		Country:user_info["country"].(string),
		Headimgurl:user_info["headimgurl"].(string),
		Unionid:user_info["unionid"].(string),
	}
	o := orm.NewOrm()
	o.Insert(user)
	o.Commit()
	return user
}

func CreateAuthSession() *Auth {
	ca, error := cache.NewCache("redis", `{"conn":":6379","dbNum":"3"}`)
	if error != nil {
		panic("链接redis服务器失败")
	}
	return &Auth{Cache: ca}
}

